﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Configuration;
using System.Data.Common;
using System.Collections.Generic;
using Oracle.ManagedDataAccess.Client;

namespace Fdb.Oracle
{
    /// <summary>
    /// 数据库操作基础类(数据层)
    /// </summary>
    public class OracleDbHelper
    {
        #region 配置数据库连接字符串

        private readonly string RETURNVALUE = "RETURNVALUE";
        private string _ConnectionString = "";
        public string ConnectionString
        {
            set
            {
                this._ConnectionString = value;
            }
            get
            {
                return this._ConnectionString;
            }
        }

        #endregion 配置数据库连接字符串

        #region 测试连接

        /// <summary>
        /// 测试连接
        /// </summary>
        /// <returns>布尔结果</returns>
        public bool ConnectionTest()
        {
            //连接字符串--Data Source=192.168.16.65:1521/orcl;User Id=用户名;Password=密码;
            using (OracleConnection connection = new OracleConnection(ConnectionString))
            {
                try
                {
                    connection.Open();
                }
                catch (Exception ex)
                {
                    return false;
                }

                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                    return true;
                }
                else
                {
                    return false;
                }
                
            }
        }

        #endregion 测试连接

        #region 检查用户名是否存在

        /// <summary>
        /// 检查用户名是否存在，存在返回true，不存在返回false
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public bool Exists(string sql)
        {
            using (OracleConnection connection = new OracleConnection(ConnectionString))
            {
                connection.Open();
                OracleCommand myCmd = new OracleCommand(sql, connection);
                myCmd.CommandTimeout = 30;
                try
                {
                    object obj = myCmd.ExecuteScalar(); //返回结果的第一行一列
                    myCmd.Parameters.Clear();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        #endregion

        #region  执行简单SQL语句

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSQL(string sql)
        {
            OracleConnection connection = null;
            OracleCommand cmd = null;
            try
            {
                connection = new OracleConnection(ConnectionString);
                cmd = new OracleCommand(sql, connection);
                cmd.CommandTimeout = 30;
                connection.Open();
                int rows = cmd.ExecuteNonQuery();
                return rows;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                }
                if (connection != null)
                {
                    connection.Close();
                    connection.Dispose();
                }
            }
        }

        #endregion

        #region   执行查询语句，返回OracleDataReader

        /// <summary>
        /// 执行查询语句，返回OracleDataReader ( 注意：调用该方法后，一定要对OracleDataReader进行Close )
        /// </summary>
        /// <param name="sql">查询语句</param>
        /// <returns>OracleDataReader</returns>
        public OracleDataReader ExecuteReader(string sql)
        {
            OracleConnection connection = new OracleConnection(ConnectionString);
            OracleCommand cmd = new OracleCommand(sql, connection);
            cmd.CommandTimeout = 30;
            object obj = "";
            try
            {
                connection.Open();
                OracleDataReader myReader = cmd.ExecuteReader();

                //try
                //{
                //    myReader.Read();
                //    obj = myReader[0];
                //    myReader.Close();
                //    myReader.Read();

                //}
                //catch
                //{
                //    Exception ex = new Exception("主键："+obj+" 连接字符串：" + ConnectionString + " SQL语句：" + strSQL);
                //    throw ex;
                //}

                return myReader;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            //finally
            //{
            //    connection.Close();

            //}
        }

        #endregion

        #region  执行SQL查询语句，返回DataTable数据表

        /// <summary>
        /// 执行SQL查询语句
        /// </summary>
        /// <param name="sqlStr"></param>
        /// <returns>返回DataTable数据表</returns>
        public void ExecuteDataTable(string sql, ref DataSet ds)
        {
            OracleConnection mycon = new OracleConnection(ConnectionString);
            OracleCommand mycmd = new OracleCommand(sql, mycon);
            mycmd.CommandTimeout = 30;
            OracleDataAdapter da = null;
            try
            {
                mycon.Open();
                da = new OracleDataAdapter(sql, mycon);
                da.Fill(ds);

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                mycon.Close();
            }
        }

        #endregion

        #region 存储过程操作

        /// <summary>
        ///  运行存储过程,返回datatable;
        /// </summary>
        /// <param name="storedProcName">存储过程名称</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public DataTable RunProcedureDatatable(string storedProcName, IDataParameter[] parameters)
        {
            using (OracleConnection connection = new OracleConnection(ConnectionString))
            {
                DataSet ds = new DataSet();
                connection.Open();
                OracleDataAdapter sqlDA = new OracleDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.Fill(ds);
                connection.Close();
                return ds.Tables[0];
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名称</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public int RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            using (OracleConnection connection = new OracleConnection(ConnectionString))
            {
                try
                {
                    connection.Open();
                    OracleCommand command = new OracleCommand(storedProcName, connection);
                    command.CommandType = CommandType.StoredProcedure;
                    foreach (OracleParameter parameter in parameters)
                    {
                        if (parameter != null)
                        {
                            // 检查未分配值的输出参数,将其分配以DBNull.Value.
                            if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                                (parameter.Value == null))
                            {
                                parameter.Value = DBNull.Value;
                            }
                            command.Parameters.Add(parameter);
                        }
                    }
                    int rows = command.ExecuteNonQuery();
                    return rows;
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                finally
                {
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 构建 OracleCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>OracleCommand</returns>
        private OracleCommand BuildQueryCommand(OracleConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            OracleCommand command = new OracleCommand(storedProcName, connection);
            command.CommandTimeout = 30;
            command.CommandType = CommandType.StoredProcedure;
            foreach (OracleParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }
            return command;
        }

        #endregion

        #region 带参数的SQL

        /// <summary>
        /// 执行命令并返回一个数据集的第一列 
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public object ExecuteScalar(string sql, DbParameter[] cmdParms)
        {
            using (OracleConnection connection = new OracleConnection(ConnectionString))
            {
                using (OracleCommand cmd = new OracleCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, sql, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }

        /// <summary>
        /// 执行带参数的sql
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="cmdParms"></param>
        /// <returns>int</returns>
        public int ExecuteSQL(string sql, OracleParameter[] cmdParms)
        {
            using (OracleConnection connection = new OracleConnection(ConnectionString))
            {
                using (OracleCommand cmd = new OracleCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, sql, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }

        /// <summary>
        /// 执行带参数的sql,返回OracleDataReader
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public void ExecuteReader(string sql, OracleParameter[] cmdParms, out OracleDataReader dataReader)
        {
            OracleConnection connection = new OracleConnection(ConnectionString);
            OracleCommand cmd = new OracleCommand();
            try
            {
                PrepareCommand(cmd, connection, null, sql, cmdParms);
                dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {
                connection.Clone();
                throw ex;
            }
        }

        /// <summary>
        /// 执行带参数的sql,返回DataTable
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="cmdParms"></param>
        /// <param name="ds"></param>
        public void ExecuteDataTable(string sql, OracleParameter[] cmdParms, ref DataSet ds)
        {
            using (OracleConnection connection = new OracleConnection(ConnectionString))
            {
                using (OracleCommand cmd = new OracleCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, sql, cmdParms);

                        using (OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(cmd))
                        {
                            oracleDataAdapter.Fill(ds);
                            cmd.Parameters.Clear();
                        }

                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }

        public void PrepareCommand(OracleCommand cmd, OracleConnection conn, OracleTransaction trans, string sql, DbParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandTimeout = 30;
            cmd.CommandText = sql;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (OracleParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

        #endregion 带参数的SQL

        #region 执行事务

        public int ExcuteTransactionSQL(string sql, OracleParameter[] cmdParms)
        {
            using (OracleConnection connection = new OracleConnection(ConnectionString))
            {
                using (OracleCommand cmd = new OracleCommand())
                {
                    OracleTransaction transaction = connection.BeginTransaction();

                    try
                    {
                        PrepareCommand(cmd, connection, transaction, sql, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        transaction.Commit();
                        return rows;
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        throw ex;
                    }
                }
            }
        }

        #endregion 执行事务

        #region 参数构造

        /// <summary>
        /// 传入输入参数
        /// </summary>
        /// <param name="ParamName">参数名称</param>
        /// <param name="DbType">参数类型</param>
        /// <param name="Size">参数大小</param>
        /// <param name="Value">参数值</param>
        /// <returns>新的parameter 对象</returns>
        public OracleParameter CreateInParam(string ParamName, OracleDbType DbType, int Size, object Value)
        {
            return CreateParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
        }

        /// <summary>
        /// 生成SQL语句参数
        /// </summary>
        /// <param name="ParamName">参数名称</param>
        /// <param name="DbType">参数类型</param>
        /// <param name="Size">参数大小</param>
        /// <param name="Direction">参数方向</param>
        /// <param name="Value">参数值</param>
        /// <returns>新的 parameter 对象</returns>
        public OracleParameter CreateParam(string ParamName, OracleDbType DbType, Int32 Size, ParameterDirection Direction, object Value)
        {
            OracleParameter param;
            ///当参数大小为0时，不使用该参数大小值
            if (Size > 0)
            {
                param = new OracleParameter(ParamName, DbType, Size);
            }
            else
            {
                ///当参数大小为0时，不使用该参数大小值
                param = new OracleParameter(ParamName, DbType);
            }
            ///创建输出类型的参数
            param.Direction = Direction;
            if (!(Direction == ParameterDirection.Output && Value == null))
            {
                param.Value = Value;
            }
            ///返回创建的参数
            return param;
        }

        #endregion 参数构造
    }
}